package com.hbisdt.cet.sample.config;

import com.hbisdt.cet.sample.entity.po.User;
import com.hbisdt.cet.sample.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.servlet.PathRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

/**
 * @Description
 * @Author Jiam
 * @Date 2025-09-22 23:22
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    /**
     * 基于内存的身份认证
     *
     * @Bean public UserDetailsService userDetailsService() {
     * UserDetails user = User.withUsername("user")
     * .password(passwordEncoder().encode("123456"))
     * .roles("USER")
     * .build();
     * UserDetails admin = User.withUsername("admin")
     * .password(passwordEncoder().encode("admin123"))
     * .roles("ADMIN")
     * .build();
     * return new InMemoryUserDetailsManager(user, admin);
     * }
     * @Bean public PasswordEncoder passwordEncoder() {
     * return new BCryptPasswordEncoder();
     * }
     **/


    /* 基于JDBC的身份认证 */
    @Autowired
    private UserMapper userMapper;

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.authorizeHttpRequests(auth -> auth
        //对static文件夹下静态资源进行统一放行
        .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
        .requestMatchers("/view/login").anonymous()
        //列表页：普通用户和管理员均可访问
        .requestMatchers("/view/index").hasAnyRole("USER", "ADMIN")
        //管理员专属路径：新增页、编辑页、相关操作接口
        .requestMatchers("/view/insert").hasRole("ADMIN")
        .requestMatchers("/view/edit/**").hasRole("ADMIN")
        .requestMatchers("/carbon/insert").hasRole("ADMIN")
        .requestMatchers("/carbon/edit").hasRole("ADMIN")
        .requestMatchers("/carbon/delete/**").hasRole("ADMIN")
        //其他所有请求：需要认证
        .anyRequest().authenticated()
    )
    .formLogin(form -> form
        .loginPage("/view/login")
        .loginProcessingUrl("/login")
        //登录成功后默认跳转到列表页
        .defaultSuccessUrl("/view/index", true)
        .failureUrl("/view/login?error=true")
        .permitAll()
    )
    .logout(logout -> logout
        .logoutUrl("/logout")
        .logoutSuccessUrl("/view/login?logout=true")
        .permitAll()
    );
    return http.build();
}

    @Bean
    public UserDetailsService userDetailsService() {
        return username -> {
            User user = userMapper.findByUsername(username);
            if (user == null) {
                throw new UsernameNotFoundException("User not found: " + username);
            }
            return user;
        };
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}

